package org.ysu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.transaction.annotation.Transactional;
import org.ysu.entity.AdminRole;
import org.ysu.mapper.AdminRoleMapper;
import org.ysu.service.AdminRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 管理员角色关联表 服务实现类
 * </p>
 *
 * @author liushuo
 * @since 2024-08-16
 */
@Service
public class AdminRoleServiceImpl extends ServiceImpl<AdminRoleMapper, AdminRole> implements AdminRoleService {


    @Resource
    AdminRoleMapper adminRoleMapper;
    //    事务：一组操作的集合，这些操作要么全部成功，要么全部失败
    @Override
    @Transactional
    public boolean save(Long roleId, Long[] adminIds) {
        UpdateWrapper<AdminRole> wrapper = new UpdateWrapper();
        wrapper.eq("role_id", roleId);
        this.remove(wrapper);
        List<AdminRole> list = new ArrayList<>();
        if (null != adminIds && adminIds.length != 0) {
            for (Long adminId : adminIds) {
                list.add(new AdminRole(adminId, roleId));
            }
        }
        return this.saveBatch(list);
    }

    @Override
    public List<AdminRole> getByRoleId(Long roleId) {
        QueryWrapper<AdminRole> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id", roleId);
        return this.list(wrapper);
    }

    @Override
    public Long getRoleId(Long adminId) {
        Long roleId = adminRoleMapper.getRoleId(adminId);
        return roleId != null ? roleId : 0L;
    }

}
